package com.example.usermanagement.controller;

import com.example.usermanagement.entity.Book;
import com.example.usermanagement.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class BookController {
    @Autowired
    private BookService bookService;

    // 显示图书列表页面
    @GetMapping("/books")  // 访问 http://localhost:8080/books
    public String showBooks(Model model) {
        model.addAttribute("books", bookService.getAllBooks());
        model.addAttribute("book", new Book()); // 为表单添加空对象
        return "Book-list";  // 对应 templates/Book-list.html 模板
    }

    // 添加图书
    @PostMapping("/books/add")  // 处理添加图书表单提交
    public String addBook(@ModelAttribute("book") Book book) {
        bookService.addBook(book);
        return "redirect:/books";  // 重定向回图书列表页面
    }
    //删除图书
    @GetMapping("/books/delete/{id}")
    public String deleteBook(@PathVariable int id) {
        bookService.deleteBook(id);
        return "redirect:/books";  // 重定向回图书列表页面
    }
    //编辑图书
    @GetMapping("/books/edit/{id}")
    public String showEditForm(@PathVariable int id, Model model) {
        Book book = bookService.getBookById(id).get();
        model.addAttribute("book", book);
        return "Book-edit";  // 对应 templates/Book-edit.html 模板
    }
    @PostMapping("/books/edit/{id}")
    public String updateBook(@ModelAttribute("book") Book book) {
        bookService.updateBook(book);
        return "redirect:/books";  // 重定向回图书列表页面
    }
}
